package com.jcbase.quartz;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcbase.core.BaseConstance;
import com.jcbase.core.task.SendCouponTask;
import com.jcbase.core.util.DateUtils;
import com.jcbase.model.RisebdCouponRule;
import com.jcbase.service.CacheService;
import com.jfinal.kit.JsonKit;

/**
 * @category 优惠券自动发送任务
 * @author yiz
 *
 */
public class CouponAutoSendJob implements Job {

	private static final Logger logger = LoggerFactory.getLogger(CouponAutoSendJob.class);

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		List<RisebdCouponRule> couponRules = RisebdCouponRule.me.getAutoCouponRule();
		if (null != couponRules && couponRules.size() > 0) {
			logger.info("开始优惠券自动发放...");
			for (RisebdCouponRule couponRule : couponRules) {
				Date startTiming = couponRule.getStartTiming();
				Date nowDate = DateUtils.getNowDateTime();
				long checkStartNowTime = DateUtils.compareIntervalDay(nowDate, startTiming);
				if (checkStartNowTime > 0) {// 继续操作，当前时间大于设置的自动发送时间
					logger.info("当前操作的couponRule={}", JsonKit.toJson(couponRule));
					Long couponNum = couponRule.getCouponNum();
					Long receiveNum = couponRule.getReceiveNum();
					String couponRuleId = couponRule.getId();
					if (0 == couponNum) {
						// 无限数量优惠券时可随便领取
						// ====找到所有未领取此优惠券的会员
						// 1.得到未领取此优惠券规则的的会员
						Set<String> noSendMemberIds = CacheService.getDiffMemberIds(BaseConstance.MEMBER_ID_SET_CACHE,
								BaseConstance.MEMBER_ID_SET_COUPONRULE_CACHE_PREFIX + couponRuleId);
						String[] noSendMemberIdArray = noSendMemberIds.toArray(new String[] {});
						// 2.开始发送,1)加入优惠券至会员优惠券表,2)修改优惠券表，优惠券状态,3)修改优惠券规则表优惠券数量
						int sendSize = noSendMemberIdArray.length;
						if (0 == sendSize) {
							continue;
						}
						SendCouponTask sendCouponTask = new SendCouponTask(0, sendSize - 1, sendSize / 100,
								noSendMemberIdArray, couponRule);
						ForkJoinPool fjpool = new ForkJoinPool();
						fjpool.execute(sendCouponTask);
						fjpool.shutdown();
						try {
							fjpool.awaitTermination(60, TimeUnit.SECONDS);
						} catch (InterruptedException e) {
							logger.error("线程被中断e={}", e);
						}
						// 3.将未发送的设置为已发送
						CacheService.addCouponRuleMemberIds(couponRuleId, noSendMemberIdArray);
					} else if (couponNum > 0 && couponNum > receiveNum) {
						// 有限数量时领取
					} else {
						logger.warn("已被领取完...");
						continue;
					}
				} else {
					continue;
				}
			}
		}
	}

}
